<template>
    <div class="app-container" style="min-height: calc(100vh - 100px - 30px) !important;">
      <div style="display: flex;height: 100%;">
        <div style="padding: 20px;background-color: #fafafa;height: 100%;border-radius: 10px;display: flex;">
            <div style="width: 80px;">
                <div>版块</div>
                <div style="margin-top: 30px;">
                    <div @click="seltp(item.id,item)" class="item" v-for="(item,index) in zltype" :class="item.id == tpid?'sel5':''">{{item.name}}</div>
                </div>
            </div>
            <div style="width: 80px;margin-left: 10px;" v-if="!ty">
                <div>年级</div>
                <div style="margin-top: 30px;">
                    <div @click="selnj(index,item.id)" v-for="(item,index) in nianji" class="item" :class="item.id == njid?'sel1':''">{{item.name}}</div>
                </div>
            </div>
            <div style="width: 80px;margin-left: 10px;" v-if="!ty">
                <div>学科</div>
                <div style="margin-top: 30px;">
                    <div @click="selxk(item.id,item)" class="item" v-for="(item,index) in nianji[njidx].xueke" :class="item.id == xkid?'sel2':''">{{item.name}}</div>
                </div>
            </div>
            <div style="width: 80px;margin-left: 10px;" v-if="!ty">
                <div>版本</div>
                <div style="margin-top: 30px;">
                    <div @click="selbb(item.id)" class="item" v-for="(item,index) in banben" :class="item.id == bbid?'sel3':''">{{item.banben}}</div>
                </div>
            </div>
            <div style="width: 80px;margin-left: 10px;">
                <div>分类</div>
                <div style="margin-top: 30px;">
                    <div @click="selxq(item.id)" class="item" v-for="(item,index) in ce" :class="item.id == xqid?'sel4':''">{{item.ceName}}</div>
                </div>
            </div>
        </div>
        <div style="padding: 20px;background-color: #fff;border-radius: 10px;height: 100%;flex: 1;">
          <el-upload
            class="tuozhuai"
            drag
            accept=".docx,.pdf"
            :data="removeNullValues(updata)"
            :headers="headers"
            :with-credentials="true"
            :action="hj+'/common/uploadZiliao'"
            :show-file-list="false"
            :on-progress="uploading"
            :on-success="uploaddone"
            :on-error="uploadError"
            :before-upload="beforeUpload"
            multiple>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将PDF、DOCX文件拖到此处，或<em>点击上传</em></div>
            <!-- <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div> -->
          </el-upload>
          <div style="margin-top: 30px;">
            <div style="display: flex;align-items: center;">
              <div style="font-size: 14px;font-weight: bold;">文件列表</div>
              <div style="margin-left: 20px;font-size: 12px;color: #8a8a8a;">共{{total}}个文件</div>
            </div>
            <div style="margin-top: 30px;">
              <div v-for="(item,index) in ziliaoList" style="display: flex;align-items: center;justify-content: space-between;margin-bottom: 30px;">
                <div style="display: flex;align-items: center;">
                  <img src="../../../assets/images/Pdf.svg" style="width: 50px;height: 50px;" alt="" srcset="">
                  <div style="margin-left: 20px;">
                    <div style="font-size: 14px;font-weight: bold;">{{item.title}}</div>
                    <div style="display: flex;align-items: center;font-size: 12px;color: #8a8a8a;margin-top: 6px;">
                      <div>文件大小：{{item.fileSize}}</div>
                      <div style="margin-left: 10px;">文件页码：{{item.pageNum}}页</div>
                      <div style="margin-left: 10px;">更新时间：{{item.addTime}}</div>
                    </div>
                  </div>
                </div>
                <div style="display: flex;align-items: center;">
                  <div @click="copyLink(item.id)" style="padding: 4px 10px;background-color: #3f82e7;color: #fff;font-size: 12px;width: fit-content;border-radius: 4px;cursor: pointer;">复制链接</div>
                  <div @click="handleDelete(item)" style="padding: 4px 10px;background-color: #e73f3f;color: #fff;font-size: 12px;width: fit-content;border-radius: 4px;cursor: pointer;margin-left: 10px;">删除</div>
                </div>
              </div>
            </div>
          </div>
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="updata.pageNum"
            :limit.sync="updata.pageSize"
            @pagination="getList"
          />
        </div>
      </div>
    </div>
  </template>

  <script>
  import { listZiliao, getZiliao, delZiliao, addZiliao, updateZiliao,getShortLink } from "@/api/ziliao/ziliao";
  import { listAllNjSon } from "@/api/ziliao/nianji";
  import { listAll } from "@/api/ziliao/banben"
  import { listCelevelAll } from "@/api/ziliao/celevel"
  import { listZiliaotypeAll } from "@/api/ziliao/ziliaotype"
  import { getToken } from "@/utils/auth";
  export default {
    name: "Ziliao",
    dicts: ['sys_vip_free', 'sys_free_pay'],
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 资料管理表格数据
        ziliaoList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          title: null,
          nianji: null,
          xueke: null,
          cetype: null,
          banben: null,
          type: null,
          yearStr: null,
          path: null,
          pageNum: null,
          free: null,
          jiage: null,
          addTime: null,
          md5: null,
          needvip: null
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {},
        nianji:[{xueke:null}],
        njid:0,
        njidx:0,
        banben:[],
        ce:[],
        zltype:[],
        xkid:0,
        bbid:0,
        xqid:0,
        tpid:0,
        hj:'/prod-api',
        headers: {
          Authorization: "Bearer " + getToken(),
        },
        updata:{
          pageNum: 1,
          pageSize: 10,
          nianji:null,
          xueke:null,
          cetype:null,
          banben:null,
          type:null
        },
        ty:false,
        xsx:false,
        // 上传相关参数
        uploadQueue: [], // 上传队列
        notificationInstances: {} // 通知实例
      };
    },
    created() {
      this.hj = process.env.VUE_APP_BASE_API
      this.getBanben()
      this.getzltype()
      //this.getList();
    },
    methods: {
      copyLink(id){
        getShortLink({id:id}).then(res=>{
          if(res.code==200){
            this.copy(res.data)
          }else{

          }
          console.log(res)
        })
      },
      copy(data) {
        let oInput = document.createElement('input')
        oInput.value = data
        document.body.appendChild(oInput)
        oInput.select() // 选择对象
        document.execCommand("Copy") // 执行浏览器复制命令
        this.$modal.msgSuccess("复制成功");
        oInput.remove()
      },
      // 上传前处理
      beforeUpload(file) {
        const fileId = file.uid;
        // 将文件添加到上传队列
        this.uploadQueue.push({
          id: fileId,
          name: file.name,
          status: 'uploading',
          progress: 0
        });

        // 显示上传进度通知，包含剩余文件数
        this.showUploadProgress(fileId, file.name, 0);
        return true;
      },

      // 上传进度更新
      uploading(e, file) {
        const fileId = file.uid;
        const progress = Math.floor(e.percent);

        // 更新队列中的进度
        const fileIndex = this.uploadQueue.findIndex(item => item.id === fileId);
        if (fileIndex !== -1) {
          this.uploadQueue[fileIndex].progress = progress;
        }

        // 更新进度通知
        this.updateUploadProgress(fileId, progress);
      },

      // 上传成功处理
      uploaddone(res, file) {
        const fileId = file.uid;

        // 从队列中移除或标记完成
        const fileIndex = this.uploadQueue.findIndex(item => item.id === fileId);
        if (fileIndex !== -1) {
          this.uploadQueue[fileIndex].status = 'success';
          this.uploadQueue[fileIndex].progress = 100;
        }

        // 更新通知为成功
        this.updateUploadNotification(fileId, 'success', '上传成功');

        // 如果是最后一个文件上传完成，则重新获取文件列表并显示上传汇总
        if (this.uploadQueue.every(item => item.status === 'success' || item.status === 'error')) {
          // 延迟执行，确保用户能看到所有上传成功的提示
          setTimeout(() => {
            this.showUploadSummary();
            this.getList();
            // 清空上传队列
            this.uploadQueue = [];
          }, 500);
        }
      },

      // 上传失败处理
      uploadError(err, file) {
        const fileId = file.uid;

        // 从队列中标记失败
        const fileIndex = this.uploadQueue.findIndex(item => item.id === fileId);
        if (fileIndex !== -1) {
          this.uploadQueue[fileIndex].status = 'error';
        }

        // 更新通知为失败
        this.updateUploadNotification(fileId, 'error', '上传失败');
      },

      // 显示上传进度通知
      showUploadProgress(fileId, fileName, progress) {
        // 计算剩余文件数
        const remainingFiles = this.uploadQueue.filter(item => item.status === 'uploading').length;

        // 创建自定义进度通知元素
        const notification = document.createElement('div');
        notification.className = 'custom-notification';
        notification.style.cssText = `
          position: fixed;
          bottom: 20px;
          right: 20px;
          width: 300px;
          background: white;
          border-radius: 4px;
          padding: 15px;
          box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
          z-index: 2050;
          display: flex;
          flex-direction: column;
        `;

        notification.innerHTML = `
          <div style="display: flex; align-items: center; justify-content: space-between;">
            <span style="font-weight: 500;">上传进度</span>
            <button class="close-btn" style="background: none; border: none; font-size: 16px; cursor: pointer;">×</button>
          </div>
          <div style="display: flex; align-items: center; justify-content: space-between; margin-top: 10px;">
            <span>${fileName}</span>
            <span class="progress-percent">${progress}%</span>
          </div>
          <div style="margin-top: 10px;">
            <div class="el-progress" style="width: 100%;">
              <div class="el-progress-bar" style="width: 100%;">
                <div class="el-progress-bar__inner" style="width: ${progress}%; background-color: #409EFF;"></div>
              </div>
            </div>
          </div>
          <div style="margin-top: 8px; font-size: 12px; color: #8a8a8a; text-align: right;">
            剩余文件: ${remainingFiles}个
          </div>
        `;

        // 关闭按钮事件
        const closeBtn = notification.querySelector('.close-btn');
        if (closeBtn) {
          closeBtn.onclick = () => {
            document.body.removeChild(notification);
            delete this.notificationInstances[fileId];
          };
        }

        document.body.appendChild(notification);
        this.notificationInstances[fileId] = notification;
      },

      // 更新上传进度
      updateUploadProgress(fileId, progress) {
        if (this.notificationInstances[fileId]) {
          const file = this.uploadQueue.find(item => item.id === fileId);
          if (file && this.notificationInstances[fileId].querySelector) {
            // 更新进度百分比
            const percentElement = this.notificationInstances[fileId].querySelector('.progress-percent');
            if (percentElement) {
              percentElement.textContent = `${progress}%`;
            }

            // 更新进度条
            const progressBar = this.notificationInstances[fileId].querySelector('.el-progress-bar__inner');
            if (progressBar) {
              progressBar.style.width = `${progress}%`;
            }

            // 更新剩余文件数
            const remainingCountElement = this.notificationInstances[fileId].querySelector('div:nth-child(4)');
            if (remainingCountElement) {
              const remainingFiles = this.uploadQueue.filter(item => item.status === 'uploading').length;
              remainingCountElement.textContent = `剩余文件: ${remainingFiles}个`;
            }
          }
        }
      },

      // 更新通知状态
      updateUploadNotification(fileId, type, message) {
        if (this.notificationInstances[fileId]) {
          const file = this.uploadQueue.find(item => item.id === fileId);
          if (file) {
            // 移除旧的自定义通知
            if (this.notificationInstances[fileId].parentNode) {
              this.notificationInstances[fileId].parentNode.removeChild(this.notificationInstances[fileId]);
            }

            // 使用封装的modal组件显示结果通知
            if (type === 'success') {
              this.$modal.notifySuccess(`${file.name} 上传成功`);
            } else {
              this.$modal.notifyError(`${file.name} 上传失败`);
            }
          }

          // 清理通知实例引用
          delete this.notificationInstances[fileId];
        }
      },

      // 显示上传汇总信息
      showUploadSummary() {
        const successFiles = this.uploadQueue.filter(item => item.status === 'success');
        const errorFiles = this.uploadQueue.filter(item => item.status === 'error');
        const totalFiles = this.uploadQueue.length;

        // 构建汇总消息
        let summaryMessage = `本次共上传 ${totalFiles} 个文件\n`;
        summaryMessage += `✓ 成功: ${successFiles.length} 个文件\n`;

        if (errorFiles.length > 0) {
          summaryMessage += `✗ 失败: ${errorFiles.length} 个文件\n`;
          summaryMessage += '失败文件列表:\n';
          errorFiles.forEach(file => {
            summaryMessage += `- ${file.name}\n`;
          });
        }

        // 创建汇总通知
        const summaryNotification = document.createElement('div');
        summaryNotification.className = 'upload-summary-notification';
        summaryNotification.style.cssText = `
          position: fixed;
          bottom: 20px;
          right: 20px;
          width: 350px;
          background: white;
          border-radius: 4px;
          padding: 15px;
          box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.15);
          z-index: 2060;
          display: flex;
          flex-direction: column;
        `;

        const statusIcon = errorFiles.length > 0 ? '❌' : '✅';
        const statusText = errorFiles.length > 0 ? '上传结果' : '上传完成';

        summaryNotification.innerHTML = `
          <div style="display: flex; align-items: center; justify-content: space-between;">
            <span style="font-weight: 500; display: flex; align-items: center;">
              ${statusIcon} ${statusText}
            </span>
            <button class="close-btn" style="background: none; border: none; font-size: 16px; cursor: pointer;">×</button>
          </div>
          <div style="margin-top: 10px; font-size: 13px; line-height: 1.6;">
            ${summaryMessage.replace(/\n/g, '<br>')}
          </div>
        `;

        // 关闭按钮事件
        const closeBtn = summaryNotification.querySelector('.close-btn');
        if (closeBtn) {
          closeBtn.onclick = () => {
            document.body.removeChild(summaryNotification);
          };
        }

        document.body.appendChild(summaryNotification);

        // 3秒后自动关闭汇总通知
        setTimeout(() => {
          if (summaryNotification.parentNode) {
            document.body.removeChild(summaryNotification);
          }
        }, 10000);
      },
      getzltype(){
        listZiliaotypeAll().then(res=>{
          this.zltype = res.data
          // this.tpid = res.data[0].id
          // this.updata.type = res.data[0].id

          let d = res.data[0].fls

          if(d!=null && d!='' && d.length>0){
            this.getce(d)
          }
          this.getNianji()
        })
      },
      getce(fls){
        listCelevelAll({fls:fls}).then(res=>{
          this.ce = res.data
          // this.xqid = res.data[0].id
          // this.updata.cetype = res.data[0].id
          // this.getList()
        })
      },
      getBanben(){
        listAll().then(res =>{
          this.banben = res.data
          // this.bbid = res.data[0].id
          // this.updata.banben = res.data[0].id
        })
      },
      selnj(index,id){
        this.xkid = null
        this.bbid = null
        this.xqid = null


        this.njid = id
        this.njidx = index
        this.updata.nianji = id
        this.getList()
      },
      selxk(id,item){

        this.bbid = null
        this.xqid = null

        this.xkid = id
        this.updata.xueke = id
        console.log(item)
        if(this.xsx&&item.fls!=null&&item.fls!=''&&item.fls.length>0){
          this.getce(item.fls)
        }else{
          this.getList()
        }
      },
      selbb(id){

        this.xqid = null

        this.bbid = id
        this.updata.banben = id
        this.getList()
      },
      selxq(id){
        this.xqid = id
        this.updata.cetype = id
        this.getList()
      },
      seltp(id,item){

        this.njid = null
        this.xkid = null
        this.bbid = null
        this.xqid = null


        let fls = item.fls

        this.tpid = id
        this.updata.type = id

        let isall = item.isall

        if(isall=='1'){
          this.ty=true

          this.updata.nianji = null
          this.updata.xueke = null
          this.updata.banben = null
          this.updata.cetype = null
          if(fls!=null&&fls.length>0){
            this.getce(fls)
          }
        }else{
          this.ty=false
          if(fls!=null&&fls.length>0){
            this.getce(fls)
          }

          let kcs = item.xks
          if(kcs!=null&&kcs.length>0){
            this.getNianji(kcs)
          }else{
            this.getNianji(null)
          }

        }

        this.getList()
      },
      getNianji(kcs){
        listAllNjSon({kcs:kcs}).then(res=>{
              this.nianji = res.data
              // this.njid = res.data[0].id
              // this.xkid = res.data[0].xueke[0].id
              // this.updata.nianji = res.data[0].id
              // this.updata.xueke = res.data[0].xueke[0].id

              let fls = res.data[0].xueke[0].fls

              if(fls!=null&&fls!=''&&fls.length>0&&kcs!=null&&kcs!=''&&kcs.length!=0){
                this.xsx = true
                this.getce(fls)
              }else{
                this.xsx = false
              }

              console.log(res.data)

          })
      },
  removeNullValues(obj) {
    return Object.keys(obj)
      .filter(key => obj[key] !== null)
      .reduce((result, key) => {
        result[key] = obj[key];
        return result;
      }, {});
  },
      /** 查询资料管理列表 */
      getList() {
        this.loading = true;

        let d = this.removeNullValues(this.updata)
        console.log(d)
        listZiliao(d).then(response => {
          this.ziliaoList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          title: null,
          nianji: null,
          xueke: null,
          cetype: null,
          banben: null,
          type: null,
          yearStr: null,
          path: null,
          pageNum: null,
          free: null,
          jiage: null,
          addTime: null,
          md5: null,
          needvip: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加资料管理";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getZiliao(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改资料管理";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateZiliao(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addZiliao(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除资料管理编号为"' + ids + '"的数据项？').then(function() {
          return delZiliao(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('ziliao/ziliao/export', {
          ...this.queryParams
        }, `ziliao_${new Date().getTime()}.xlsx`)
      }
    }
  };
  </script>
  <style lang="scss">
    .item{
        padding: 4px 0;border: 1px solid #7a7a7a;border-radius: 4px;text-align: center;margin-bottom: 20px;color: #7a7a7a;background-color: #eeeeee;cursor: pointer;
        font-size: 12px;
    }
    .sel1 {
        color: #fff !important;
        background-color: #1984ff;
        border-color: #1984ff;
    }
    .sel2 {
        color: #fff !important;
        background-color: #ff4f19;
        border-color: #ff4f19;
    }
    .sel3 {
        color: #fff !important;
        background-color: #20912f;
        border-color: #20912f;
    }
    .sel4 {
        color: #fff !important;
        background-color: #ff1919;
        border-color: #ff1919;
    }
    .sel5 {
        color: #fff !important;
        background-color: #0ead93;
        border-color: #0ead93;
    }
    .tuozhuai {
      width: 100%;
      .el-upload {
        width: 100% !important;
        .el-upload-dragger {
          width: 100% !important;
        }
      }
    }
  </style>
